﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BaHuan.BusinessLayer;
using BaHuan.Common;
using BaHuan.Entities;
using BaHuan.Utils;

namespace BaHuan
{
    public partial class FrmPhieuXuatKho : Form
    {
        #region Khai bao toan cuc

        private PhieuXuatKhoManagement phieuxuatkhoMgt = new PhieuXuatKhoManagement();
        private ChiNhanhCongTyMgt chinhanhcongtyMgt = new ChiNhanhCongTyMgt();
        private HangHoaManagement hanghoaMgt = new HangHoaManagement();
        private CTPhieuXuatKhoManagement ctphieuxuatkhoMgt = new CTPhieuXuatKhoManagement();
        private DonGiaNguyenVatLieuManagement dongianguyenvatlieuMgt = new DonGiaNguyenVatLieuManagement();
        private QuanLyKhoManagement quanlykhoMgt = new QuanLyKhoManagement();
        private KhoManagement khoMgt = new KhoManagement();
        private CTKhoManagement ctKhoMgt = new CTKhoManagement();
        private BangMaPhieuMgt bangmaphieuMgt = new BangMaPhieuMgt();
        private DonViTinhMgt donvitinhMgt = new DonViTinhMgt();
        private ButToanMgt buttoanMgt = new ButToanMgt();

        private DonGiaNguyenVatLieu dongianguyenvatlieu = new DonGiaNguyenVatLieu();
        private List<CTPhieuXuatKho> lstDeleteCTPhieuXuatKho = new List<CTPhieuXuatKho>();
        private HangHoa vatlieu = new HangHoa();
        private PhieuXuatKho phieuxuatkho;
        private List<HangHoa> hanghoacu = new List<HangHoa>();
        private int IdPhieuXuatKho;

        public PhieuXuatKho PhieuXuatKho
        {
            set { this.phieuxuatkho = value; }
            get { return this.phieuxuatkho; }
        }

        private DateTime dtOld = new DateTime();
        private string prefixOld = "";

        private int idLoaiPhieu = 7;
        public string sNoiLuu = "";
        bool IsEdited = false;
        bool IsReturned = true;

        public int EditButtonClick = 0;

        private NhanVien nhanvien;
        public NhanVien NhanVien
        {
            set { this.nhanvien = value; }
            get { return this.nhanvien; }
        }

        #endregion

        #region Xu ly Load
        public FrmPhieuXuatKho()
        {
            InitializeComponent();
        }

        public FrmPhieuXuatKho(NhanVien nv)
        {
            InitializeComponent();
            this.nhanvien = nv;
            txtNguoiLap.Text = nhanvien.HoTen;
        }

        public FrmPhieuXuatKho(NhanVien nv, PhieuXuatKho pxk)
        {
            InitializeComponent();
            this.nhanvien = nv;
            txtNguoiLap.Text = nhanvien.HoTen; 
            this.phieuxuatkho = pxk;
            IdPhieuXuatKho = this.phieuxuatkho.Id;
            IsEdited = false;
            lbID.Text = this.phieuxuatkho.Id.ToString();
        }

        private void FrmPhieuXuatKho_Load(object sender, EventArgs e)
        {
            gpbThongTin.Enabled = false;
            dgvChiTiet.AutoGenerateColumns = false;
            dgvChiTiet.ReadOnly = true;
            ChangeStatusControl(true, gpbThongTin);

            btnIn.Enabled = false;
            btnDinhKhoan.Enabled = false;
            btnLuu.Enabled = true;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;

            cboKhoXuat.DataSource = GetAllChiNhanhCongTy();
            cboKhoXuat.DisplayMember = "TenChiNhanh";
            cboKhoXuat.ValueMember = "Id";

            cboPrefix.DataSource = GetAllBangMaPhieu(idLoaiPhieu);
            cboPrefix.DisplayMember = "MaSo";
            cboPrefix.ValueMember = "Id";

            cboDonViTinh.DataSource = GetAllDonViTinh();
            cboDonViTinh.DisplayMember = "TenDVT";
            cboDonViTinh.ValueMember = "Id";

            if (EditButtonClick == 1)
            {
                dtOld = phieuxuatkho.NgayThang;
                dtNgayXuat.Value = phieuxuatkho.NgayThang;

                prefixOld = phieuxuatkho.Prefix;
                cboPrefix.Text = phieuxuatkho.Prefix;
                txtMaPhieu.Text = phieuxuatkho.OrderNumber;
                
                txtNguoiLap.Text = phieuxuatkho.NguoiLapPhieu;
                txtBoPhan.Text = phieuxuatkho.BoPhan;
                txtNguoiNhan.Text = phieuxuatkho.NguoiNhan;
                cboKhoXuat.SelectedValue = phieuxuatkho.IdChiNhanhCongTy;
                txtLyDo.Text = phieuxuatkho.LyDo;
                txtKemTheo.Text = phieuxuatkho.ChungTuKemTheo;

                UpdateGridview();
                btnIn.Enabled = true;
                btnDinhKhoan.Enabled = true;
                btnSua.Enabled = true;
                btnXoa.Enabled = true;
                btnLuu.Enabled = false;
            }
        }

        private void UpdateGridview()
        {
            List<CTPhieuXuatKho> ctpnk = (from ctpn in GetAllCTPhieuXuatKho()
                                          where ctpn.IdPhieuXuatKho == phieuxuatkho.Id
                                          select ctpn).ToList();

            dgvChiTiet.DataSource = null;
            foreach (CTPhieuXuatKho ct in ctpnk)
            {
                DataGridViewRow row = new DataGridViewRow();

                DataGridViewCell cell1 = new DataGridViewTextBoxCell();
                cell1.Value = ct.TenHang;
                row.Cells.Add(cell1);

                DataGridViewCell cell2 = new DataGridViewTextBoxCell();
                cell2.Value = ct.MaHang;
                row.Cells.Add(cell2);

                DataGridViewComboBoxCell cell3 = new DataGridViewComboBoxCell();
                cell3.DataSource = GetAllDonViTinh();
                cell3.DisplayMember = "TenDVT";
                cell3.ValueMember = "Id";
                cell3.Value = ct.DonViTinh;
                row.Cells.Add(cell3);

                DataGridViewCell cell4 = new DataGridViewTextBoxCell();
                cell4.Value = ct.SoLuong;
                row.Cells.Add(cell4);
                DataGridViewCell cell5 = new DataGridViewTextBoxCell();
                cell5.Value = ct.DonGia;
                row.Cells.Add(cell5);
                DataGridViewCell cell6 = new DataGridViewTextBoxCell();
                cell6.Value = ct.ThanhTien;
                row.Cells.Add(cell6);
                DataGridViewCell cell7 = new DataGridViewTextBoxCell();
                cell7.Value = ct.Id;
                row.Cells.Add(cell7);

                dgvChiTiet.Rows.Add(row);
            }
        }
        #endregion

        #region Xu ly cac Button
        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            RefreshControl();
            IsEdited = false;
            lbID.Text = "";
            EnableEdit();
            txtNguoiLap.Text = nhanvien.HoTen;
            dtNgayXuat.Select();
            prefixOld = "";
            txtMaPhieu.Text = "";
        }

        private void EnableEdit()
        {               
            gpbThongTin.Enabled = true;
            ChangeStatusTextBox(false);
            ChangeStatusControl(false, gpbThongTin);

            dgvChiTiet.ReadOnly = false;
            btnLuu.Enabled = true;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
            btnDinhKhoan.Enabled = false;
            btnIn.Enabled = false;

            dgvChiTiet.Columns[1].ReadOnly = true;
            //dgvChiTiet.Columns[5].ReadOnly = true;
        }

        private void DisableEdit()
        {
            gpbThongTin.Enabled = false;

            ChangeStatusTextBox(true);
            ChangeStatusControl(true, gpbThongTin);

            dgvChiTiet.ReadOnly = true;
            btnLuu.Enabled = false;
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            InsertUpdate();
        }

        private void InsertUpdate()
        {
            if (txtMaPhieu.Text == "")
            {
                MessageBox.Show("Vui lòng chọn mã phiếu");
                return;
            }

            if (dgvChiTiet.Rows.Count <=1 ||  txtBoPhan.Text == "" || txtNguoiNhan.Text == "")
            {
                MessageBox.Show("Vui lòng nhập đầy đủ thông tin !", "Thông báo"); ;
                return;
            }

            if (dgvChiTiet.Rows.Count > 1)
            {
                for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                {
                    if (dgvChiTiet.Rows[i].Cells[0].Value == null || dgvChiTiet.Rows[i].Cells[2].Value == null)
                    {
                        MessageBox.Show("Vui lòng nhập thông tin trong danh sách !", "Thông báo");
                        return;
                    }
                }

                ResultObj result = new ResultObj();

                string sMaSo = cboPrefix.Text + "/" + dtNgayXuat.Value.ToString("MM") + dtNgayXuat.Value.ToString("yy") + "/" + txtMaPhieu.Text;
                DateTime Ngaythang = dtNgayXuat.Value;
                string sNguoilap = txtNguoiLap.Text;
                string sNguoinhan = txtNguoiNhan.Text;
                string sLydo = txtLyDo.Text;
                string sKemtheo = txtKemTheo.Text;
                string sDiachi = txtDiaChi.Text;
                string sBophan = txtBoPhan.Text;

                phieuxuatkho = new PhieuXuatKho();

                phieuxuatkho.Id = IdPhieuXuatKho;
                phieuxuatkho.Prefix = cboPrefix.Text;
                phieuxuatkho.OrderNumber = txtMaPhieu.Text;
                phieuxuatkho.IdChiNhanhCongTy = ((ChiNhanhCongTy)cboKhoXuat.SelectedItem).Id;
                phieuxuatkho.MaSo = sMaSo;
                phieuxuatkho.History = "";
                phieuxuatkho.NgayThang = Ngaythang;
                phieuxuatkho.NguoiLapPhieu = sNguoilap;
                phieuxuatkho.NguoiNhan = sNguoinhan;
                phieuxuatkho.LyDo = sLydo;
                phieuxuatkho.ChungTuKemTheo = sKemtheo;
                phieuxuatkho.BoPhan = sBophan;
                phieuxuatkho.IsDelete = 0;

                // Trường hợp bấm nút Lưu
                if (!IsEdited)
                {
                    result = phieuxuatkhoMgt.SaveNewPhieuXuatKho(phieuxuatkho);
                    lbID.Text = result.ReturnCode.ToString();

                    ResultObj resultObj = new ResultObj();
                    resultObj = phieuxuatkhoMgt.GetPhieuXuatKhoByMaSo(phieuxuatkho);
                    List<PhieuXuatKho> lstPhieuXuatKho = (List<PhieuXuatKho>)resultObj.Result;

                    if (lstPhieuXuatKho.Count > 0)
                    {
                        for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                        {
                            CTPhieuXuatKho ctPhieuXuatKho = new CTPhieuXuatKho();
                            ctPhieuXuatKho.IdPhieuXuatKho = lstPhieuXuatKho[0].Id;
                            ctPhieuXuatKho.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                            ctPhieuXuatKho.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                            ctPhieuXuatKho.DonViTinh = Convert.ToString((dgvChiTiet.Rows[i].Cells[2] as DataGridViewComboBoxCell).FormattedValue.ToString());
                            ctPhieuXuatKho.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                            ctPhieuXuatKho.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value);
                            ctPhieuXuatKho.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value);
                            ctPhieuXuatKho.IsDelete = 0;

                            result = ctphieuxuatkhoMgt.SaveNewCTPhieuXuatKho(ctPhieuXuatKho);
                        }
                    }
                }
                // Trường hợp bấm nút Edit
                else
                {
                    phieuxuatkho.Id = Convert.ToInt32(lbID.Text);

                    List<CTPhieuXuatKho> lst = (from p in GetAllCTPhieuXuatKho()
                                                where p.IdPhieuXuatKho == phieuxuatkho.Id
                                                select p).ToList();

                    List<QuanLyKho> QLKho = (from k in GetAllQuanLyKho()
                                             where k.SoChungTuXuat == phieuxuatkho.MaSo
                                             select k).ToList();

                    foreach (QuanLyKho qlk in QLKho)
                    {
                        qlk.IsDelete = 1;
                        result = quanlykhoMgt.UpdateQuanLyKho(qlk);

                        HangHoa hanghoa = (from h in GetAllHangHoa()
                                           where h.Id == qlk.IdHangHoa && h.NoiLuuTru == ((ChiNhanhCongTy)cboKhoXuat.SelectedItem).TenChiNhanh
                                           select h).FirstOrDefault();

                        if (!hanghoa.Equals(null))
                        {
                            int index = lst.FindIndex(p => p.MaHang == hanghoa.MaSo);
                            hanghoa.SoLuong += lst[index].SoLuong;
                            result = hanghoaMgt.UpdateHangHoa(hanghoa);
                        }
                    }

                    result = phieuxuatkhoMgt.UpdatePhieuXuatKho(phieuxuatkho);

                    for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                    {
                        if (dgvChiTiet.Rows[i].Cells[0].Value != DBNull.Value)
                        {
                            CTPhieuXuatKho ctPhieuXuatKho = new CTPhieuXuatKho();
                            ctPhieuXuatKho.IdPhieuXuatKho = phieuxuatkho.Id;
                            ctPhieuXuatKho.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                            ctPhieuXuatKho.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                            ctPhieuXuatKho.DonViTinh = Convert.ToString((dgvChiTiet.Rows[i].Cells[2] as DataGridViewComboBoxCell).FormattedValue.ToString());
                            ctPhieuXuatKho.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value);
                            ctPhieuXuatKho.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value);
                            ctPhieuXuatKho.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value);

                            if (dgvChiTiet.Rows[i].Cells[6].Value != null)
                            {
                                ctPhieuXuatKho.Id = Convert.ToInt32(dgvChiTiet.Rows[i].Cells[6].Value);
                                result = ctphieuxuatkhoMgt.UpdateCTPhieuXuatKho(ctPhieuXuatKho);
                            }
                            else
                            {
                                result = ctphieuxuatkhoMgt.SaveNewCTPhieuXuatKho(ctPhieuXuatKho);
                                dgvChiTiet.Rows[i].Cells[6].Value = result.ReturnCode;
                            }
                        }
                    }
                }


                //Nếu Lưu hoặc sửa thành công , tiếp tục cập nhật Quản lý kho và Hàng hóa

                if (result.ReturnCode > 0)
                {
                    phieuxuatkho.Id = result.ReturnCode;

                    MessageBox.Show("Lưu thành công", "Thông báo");

                    int id = ((ChiNhanhCongTy)cboKhoXuat.SelectedItem).Id;
                    CTKho lstCTKho = (from ctkho in GetAllCTKho()
                                            where ctkho.Id == id
                                            select ctkho).First();

                    List<Kho> lstKho = (from kh in GetAllKho()
                                        where kh.Id == lstCTKho.IdKho
                                        select kh).ToList();

                    try
                    {
                        for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                        {
                            List<HangHoa> lstHangHoa = (from hh in GetAllHangHoa()
                                                        where hh.MaSo == dgvChiTiet.Rows[i].Cells[1].Value.ToString() &&
                                                               hh.NoiLuuTru == ((ChiNhanhCongTy)cboKhoXuat.SelectedItem).TenChiNhanh.ToString()
                                                        select hh).ToList();

                            if (lstHangHoa.Count > 0 && lstKho.Count > 0)
                            {
                                QuanLyKho quanlykho = new QuanLyKho();
                                quanlykho.IdKho = lstKho[0].Id;
                                quanlykho.IdHangHoa = lstHangHoa[0].Id;
                                quanlykho.SoChungTuNhap = "";
                                quanlykho.SoChungTuXuat = phieuxuatkho.MaSo;
                                quanlykho.IsDelete = 0;
                                ResultObj rsObj = new ResultObj();
                                rsObj = quanlykhoMgt.SaveNewQuanLyKho(quanlykho);

                                lstHangHoa[0].SoLuong -= Convert.ToInt32(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                                hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                            }
                            else
                            {
                                MessageBox.Show("Không thể cập nhật lại quản lý kho và hàng hóa", "Thông báo!");
                            }
                        }
                    }
                    catch { }

                    //delete cac CTPhieuXuatKho do nguoi dung chuot phai "XOA"
                    if (this.lstDeleteCTPhieuXuatKho.Count > 0)
                    {
                        foreach (CTPhieuXuatKho ct in this.lstDeleteCTPhieuXuatKho)
                        {
                            ct.IsDelete = 1;
                            ctphieuxuatkhoMgt.UpdateCTPhieuXuatKho(ct);
                        }
                    }

                    btnDinhKhoan.Enabled = true;
                    btnSua.Enabled = true;
                    btnXoa.Enabled = true;
                    btnLuu.Enabled = false;
                }
                
                else if (result.ReturnCode == Definitions.DUPLICATED_VALUE)
                    MessageBox.Show("Dữ liệu bị trùng", "Thông báo");
                else
                    MessageBox.Show("Thất bại");
                IsEdited = false;
            }
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            EnableEdit();
            btnSua.Enabled = false;
            btnLuu.Enabled = true;
            btnXoa.Enabled = false;
            btnDinhKhoan.Enabled = false;
            IsEdited = true;
        }

        public void EditOrRemoveDinhKhoan(string MaSo)
        {
            ResultObj resultObj = new ResultObj();

            List<ButToan> lst = (from p in GetAllButToan()
                                 where p.SoChungTu == MaSo
                                 select p).ToList();

            if (lst.Count > 0)
            {
                foreach (ButToan b in lst)
                {
                    b.IsEdited = 1;
                    resultObj = buttoanMgt.UpdateButToan(b);
                }
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("Bạn chắc chắn muốn xóa?", "Thông báo!", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                //Delete Phiếu xuất kho
                phieuxuatkho.IsDelete = 1;
                phieuxuatkhoMgt.UpdatePhieuXuatKho(phieuxuatkho);


                //Delete Chi tiết phiếu xuất kho

                List<CTPhieuXuatKho> lst = (from p in GetAllCTPhieuXuatKho()
                                            where p.IdPhieuXuatKho == phieuxuatkho.Id
                                            select p).ToList();
                if (lst.Count > 0)
                {
                    foreach (CTPhieuXuatKho ct in lst)
                    {
                        ct.IsDelete = 1;
                        ctphieuxuatkhoMgt.UpdateCTPhieuXuatKho(ct);
                    }
                }

                List<QuanLyKho> QLKho = (from k in GetAllQuanLyKho()
                                         where k.SoChungTuXuat == phieuxuatkho.MaSo
                                         select k).ToList();
                if (QLKho.Count > 0)
                {
                    foreach (QuanLyKho qlk in QLKho)
                    {
                        qlk.IsDelete = 1;
                        quanlykhoMgt.UpdateQuanLyKho(qlk);

                        HangHoa hanghoa = (from h in GetAllHangHoa()
                                           where h.Id == qlk.IdHangHoa && h.NoiLuuTru == ((ChiNhanhCongTy)cboKhoXuat.SelectedItem).TenChiNhanh
                                           select h).FirstOrDefault();

                        int index = lst.FindIndex(p => p.MaHang == hanghoa.MaSo);
                        hanghoa.SoLuong += lst[index].SoLuong;
                        hanghoaMgt.UpdateHangHoa(hanghoa);
                    }
                }

                string maPhieu = cboPrefix.Text + "/" + dtNgayXuat.Value.ToString("MM") + dtNgayXuat.Value.ToString("yy") + "/" + txtMaPhieu.Text;
                EditOrRemoveDinhKhoan(maPhieu);

                MessageBox.Show("Đã xóa","Thông báo");
            }
            else if (dialogResult == DialogResult.No)
            {
                return;
            }
        }

        private void btnDinhKhoan_Click(object sender, EventArgs e)
        {
            PhieuXuatKho phieuxuatkho = new PhieuXuatKho();

            phieuxuatkho.MaSo = cboPrefix.Text + "/" + dtNgayXuat.Value.ToString("MM") + dtNgayXuat.Value.ToString("yy") + "/" + txtMaPhieu.Text;
            phieuxuatkho.NguoiLapPhieu = txtNguoiLap.Text;
            phieuxuatkho.NguoiNhan = txtNguoiNhan.Text;
            phieuxuatkho.LyDo = txtLyDo.Text;
            phieuxuatkho.BoPhan = txtBoPhan.Text;
            phieuxuatkho.IdChiNhanhCongTy = ((ChiNhanhCongTy)cboKhoXuat.SelectedItem).Id;
            phieuxuatkho.listCTPhieuXuatKho = new List<CTPhieuXuatKho>();

            long tien = 0;
            for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
            {
                tien = tien + Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value);
                CTPhieuXuatKho ctphieuxuatkho = new CTPhieuXuatKho();

                ctphieuxuatkho.TenHang = dgvChiTiet.Rows[i].Cells[0].Value.ToString();
                ctphieuxuatkho.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                ctphieuxuatkho.DonViTinh = Convert.ToString(dgvChiTiet.Rows[i].Cells[2].FormattedValue);
                ctphieuxuatkho.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value);
                ctphieuxuatkho.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value);
                ctphieuxuatkho.ThanhTien = tien;

                phieuxuatkho.listCTPhieuXuatKho.Add(ctphieuxuatkho);
            }

            FrmDinhKhoanPhieuXuatKho frmDinhKhoanPhieuXuatKho = new FrmDinhKhoanPhieuXuatKho(tien);
            frmDinhKhoanPhieuXuatKho.PhieuXuatKho = phieuxuatkho;
            frmDinhKhoanPhieuXuatKho.Show();
            btnIn.Enabled = true;
        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            FrmXemReport frm = new FrmXemReport(Convert.ToInt32(lbID.Text));
            this.Hide();
            frm.ShowDialog();
            this.Show();
        }
        #endregion

        #region Xu ly cac Event

        private void dgvChiTiet_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = false;
        }

        private void cboPrefix_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (prefixOld != ((BangMaPhieu)cboPrefix.SelectedItem).MaSo)
                txtMaPhieu.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtNgayXuat.Value);
        }

        private void dtNgayXuat_ValueChanged(object sender, EventArgs e)
        {
            if (dtOld != dtNgayXuat.Value)
                txtMaPhieu.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtNgayXuat.Value);
        }

        private void cboKhoXuat_SelectedValueChanged(object sender, EventArgs e)
        {
            txtDiaChi.Text = ((ChiNhanhCongTy)cboKhoXuat.SelectedItem).DiaChiChiNhanh;
            dgvChiTiet.Rows.Clear();
        }
    
        private void dgvChiTiet_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 3 && e.RowIndex > -1)
            {
                try
                {
                    int num;
                    if (dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
                        dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                    if (!Int32.TryParse(dgvChiTiet.CurrentRow.Cells[3].Value.ToString(), out num))
                    {
                        MessageBox.Show("Vui lòng nhập số !", "Thông báo");
                        dgvChiTiet.CurrentRow.Cells[3].Value = null;
                        dgvChiTiet.CurrentCell = dgvChiTiet.CurrentRow.Cells[3];
                        return;
                    }
                }
                catch
                {
                    return;
                }
            }
            ResultObj result = new ResultObj();
            result = hanghoaMgt.GetAllHangHoa();
            List<HangHoa> lstVatLieu = (List<HangHoa>)result.Result;

            #region Kiểm tra cell Tên hàng
            if (e.ColumnIndex == 0 && e.RowIndex != -1)
            {
                if (this.IsReturned)
                {
                    try
                    {
                        sNoiLuu = ((ChiNhanhCongTy)cboKhoXuat.SelectedItem).TenChiNhanh.ToString();
                        string sTimKiem = "";
                        string sMaKho = cboKhoXuat.SelectedValue.ToString();

                        sTimKiem = dgvChiTiet.CurrentRow.Cells[0].Value.ToString();

                        HangHoa h = (from c in GetAllHangHoa()
                                      where c.Ten == sTimKiem
                                      select c).FirstOrDefault();

                        if (h == null && dgvChiTiet.CurrentRow.Cells[6].Value == null)
                        {
                            FrmTimKiemHangHoa frmTimKiemHangHoa = new FrmTimKiemHangHoa(sTimKiem, sMaKho, sNoiLuu);
                            frmTimKiemHangHoa.formclosetimkiemhanghoa += new FormCloseTimKiemHangHoa(frmTimKiemHangHoa_formclosetimkiemhanghoa);
                            frmTimKiemHangHoa.ShowDialog();
                            this.IsReturned = true;
                        }

                        if (dgvChiTiet.CurrentRow.Cells[1].Value != null)
                        {
                            HangHoa hanghoa = (from hh in GetAllHangHoa()
                                               where hh.MaSo == dgvChiTiet.CurrentRow.Cells[1].Value.ToString()
                                               select hh).FirstOrDefault();

                            dgvChiTiet.Rows[e.RowIndex].Cells[4].Value = hanghoa.DonGia;
                            dgvChiTiet.Rows[e.RowIndex].Cells[1].Value = hanghoa.MaSo;
                        }
                        else
                        {
                            dgvChiTiet.CurrentRow.Cells[1].Value = null;
                            dgvChiTiet.CurrentRow.Cells[0].Value = null;
                        }
                    }
                    catch
                    {
                        return;
                    }
                }
            }
            #endregion

            #region Kiểm tra cell Mã Hàng
            if (e.ColumnIndex == 1 && e.RowIndex != -1)
            {
                try
                {
                    string ma = dgvChiTiet.CurrentRow.Cells[1].Value.ToString();

                    HangHoa hh = (from lsthh in GetAllHangHoa()
                                  where lsthh.MaSo == ma
                                  select lsthh).First();
                    dgvChiTiet.CurrentRow.Cells[0].Value = hh.Ten;
                }
                catch
                {
                    return;
                }
            }
            #endregion

            if ((e.ColumnIndex == 3 || e.ColumnIndex==4) && e.RowIndex != -1)
            {
                try
                {
                    long thanhtien = 0;
                    long socay = Convert.ToInt64(dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString());
                    //long sotrung = socay * 300;
                    //dgvChiTiet.Rows[e.RowIndex].Cells[3].Value = sotrung.ToString();
                    long dongia = Convert.ToInt64(dgvChiTiet.Rows[e.RowIndex].Cells[4].Value.ToString());
                    thanhtien = socay * dongia;
                    dgvChiTiet.Rows[e.RowIndex].Cells[5].Value = thanhtien.ToString();
                }
                catch
                {
                    return;
                }
            }
        }

        public void frmTimKiemHangHoa_formclosetimkiemhanghoa(string MaSo, string sTen, bool IsReturn)
        {
            this.IsReturned = IsReturn;
            dgvChiTiet.CurrentRow.Cells[0].Value = sTen;
            dgvChiTiet.CurrentRow.Cells[1].Value = MaSo;
        }

        public void ChangeStatusTextBox(bool IsReadOnly)
        {
            if (IsReadOnly)
            {
                txtMaPhieu.ReadOnly = true;
                txtNguoiLap.ReadOnly = true;
                txtNguoiNhan.ReadOnly = true;
                txtLyDo.ReadOnly = true;
                txtKemTheo.ReadOnly = true;
                txtDiaChi.ReadOnly = true;
                txtBoPhan.ReadOnly = true;
            }
            else
            {
                txtMaPhieu.ReadOnly = false;
                txtNguoiLap.ReadOnly = false;
                txtNguoiNhan.ReadOnly = false;
                txtLyDo.ReadOnly = false;
                txtKemTheo.ReadOnly = false;
                txtDiaChi.ReadOnly = false;
                txtBoPhan.ReadOnly = false;
            }
        }

        public void ChangeStatusControl(bool IsReadOnly, Control control)
        {
            foreach (Control c in control.Controls)
            {
                if (c is TextBox)
                {
                    if (IsReadOnly)
                    {
                        ((TextBox)c).ReadOnly = true;
                    }
                    else
                    {
                        ((TextBox)c).ReadOnly = false;
                    }
                }
                else if (c is ComboBox)
                {
                    if (IsReadOnly)
                    {
                        ((ComboBox)c).Enabled = false;
                    }
                    else
                    {
                        ((ComboBox)c).Enabled = true;
                    }
                }
                else if (c is DateTimePicker)
                {
                    if (IsReadOnly)
                    {
                        ((DateTimePicker)c).Enabled = false;
                    }
                    else
                    {
                        ((DateTimePicker)c).Enabled = true;
                    }
                }
            }
        }

        public void ClearControl(Control control)
        {
            foreach (Control c in control.Controls)
            {
                if (c is TextBox)
                {
                    ((TextBox)c).Clear();
                }
                else if (c is ComboBox)
                {
                    switch (c.Name)
                    {
                        case "cboKhoXuat":
                            cboKhoXuat.DataSource = GetAllChiNhanhCongTy();
                            cboKhoXuat.DisplayMember = "TenChiNhanh";
                            break;
                    }
                }

                if (c.HasChildren)
                {
                    ClearControl(c);
                }
            }
        }

        public void RefreshControl()
        {
            dgvChiTiet.Rows.Clear();
            txtKemTheo.Clear();
            txtLyDo.Clear();
            txtBoPhan.Clear();
            txtNguoiNhan.Clear();

            dtNgayXuat.Value = DateTime.Now;
            cboPrefix.Text = "";
        }

        private void XoaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvChiTiet.CurrentRow != null)
            {
                if (dgvChiTiet.CurrentRow.Index != (dgvChiTiet.Rows.Count - 1))
                {
                    if (dgvChiTiet.CurrentRow.Cells[6].Value != null)
                    {
                        int id = Convert.ToInt32(dgvChiTiet.CurrentRow.Cells[6].Value.ToString());

                        CTPhieuXuatKho ctPhieuXuatKho = (from ct in GetAllCTPhieuXuatKho()
                                                         where ct.Id == id
                                                         select ct).FirstOrDefault();

                        if (ctPhieuXuatKho != null)
                        {
                            if (!lstDeleteCTPhieuXuatKho.Contains(ctPhieuXuatKho))
                                lstDeleteCTPhieuXuatKho.Add(ctPhieuXuatKho);
                        }
                    }
                }

                dgvChiTiet.Rows.RemoveAt(dgvChiTiet.CurrentRow.Index);
            }
        }

        private void dgvChiTiet_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                DataGridView.HitTestInfo hti = dgvChiTiet.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    dgvChiTiet.ClearSelection();
                    dgvChiTiet.CurrentCell = dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    dgvChiTiet.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }

        private void cboKhoXuat_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhCongTy b in cboKhoXuat.Items)
            {
                if (b.TenChiNhanh.ToLower().Contains(cboKhoXuat.Text) && cboKhoXuat.Text != "")
                {
                    cboKhoXuat.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboKhoXuat.SelectedValue == null)
            {
                cboKhoXuat.Text = "";
            }
        }

        #endregion

        #region Get Lists

        public List<ChiNhanhCongTy> GetAllChiNhanhCongTy()
        {
            ResultObj result = new ResultObj();
            result = chinhanhcongtyMgt.GetAllChiNhanhCongTy();
            List<ChiNhanhCongTy> lstChiNhanhCongTy = (List<ChiNhanhCongTy>)result.Result;
            return lstChiNhanhCongTy;
        }

        public List<HangHoa> GetAllHangHoa()
        {
            ResultObj result = new ResultObj();
            result = hanghoaMgt.GetAllHangHoa();
            List<HangHoa> lstHangHoa = (List<HangHoa>)result.Result;
            return lstHangHoa;
        }

        public List<DonGiaNguyenVatLieu> GetAllDonGiaNguyenVatLieu()
        {
            ResultObj result = new ResultObj();

            result = dongianguyenvatlieuMgt.GetAllDonGiaNguyenVatLieu();
            List<DonGiaNguyenVatLieu> lstDonGiaNguyenVatLieu = (List<DonGiaNguyenVatLieu>)result.Result;

            return lstDonGiaNguyenVatLieu;
        }

        public List<CTPhieuXuatKho> GetAllCTPhieuXuatKho()
        {
            ResultObj result = new ResultObj();

            result = ctphieuxuatkhoMgt.GetAllCTPhieuXuatKho();
            List<CTPhieuXuatKho> lstCTPhieuXuatKho = (List<CTPhieuXuatKho>)result.Result;

            return lstCTPhieuXuatKho;
        }

        public List<Kho> GetAllKho()
        {
            ResultObj result = new ResultObj();
        result = khoMgt.GetAllKho();
            List<Kho> lstKho = (List<Kho>)result.Result;
            return lstKho;
        }

        public List<QuanLyKho> GetAllQuanLyKho()
        {
            ResultObj resultObj = new ResultObj();
            List<QuanLyKho> lstQuanLyKho = new List<QuanLyKho>();

            resultObj = quanlykhoMgt.GetAllQuanLyKho();
            lstQuanLyKho = (List<QuanLyKho>)resultObj.Result;

            return lstQuanLyKho;
        }

        public List<CTKho> GetAllCTKho()
        {
            ResultObj resultObj = new ResultObj();
            List<CTKho> lstCTKho = new List<CTKho>();

            resultObj = ctKhoMgt.GetAllCTKho();
            lstCTKho = (List<CTKho>)resultObj.Result;

            return lstCTKho;
        }

        public List<BangMaPhieu> GetAllBangMaPhieu(int id)
        {
            ResultObj resultObj = new ResultObj();

            resultObj = bangmaphieuMgt.GetAllBangMaPhieuByIDLoaiPhieu(id);
            List<BangMaPhieu> listBangMaPhieu = (List<BangMaPhieu>)resultObj.Result;

            return listBangMaPhieu;
        }

        public List<ButToan> GetAllButToan()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = buttoanMgt.GetAllButToan();
            List<ButToan> listButToan = (List<ButToan>)resultObj.Result;

            return listButToan;
        }

        public List<DonViTinh> GetAllDonViTinh()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = donvitinhMgt.GetAllDonViTinh();
            List<DonViTinh> listDonViTinh = (List<DonViTinh>)resultObj.Result;

            return listDonViTinh;
        }
      
        #endregion
    }
}

